package com.pxst.integration.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.pxst.exception.BusinessException;
import com.pxst.integration.entity.SysSelectOptionConfigEntity;
import com.pxst.integration.mapper.SysSelectOptionConfigEntityMapper;
import com.pxst.integration.resp.IntegrationResult;
import com.pxst.integration.service.SysSelectOptionConfigEntityService;
import com.pxst.merchant.entity.SysMerchantInfoEntity;
import com.pxst.merchant.mapper.SysMerchantInfoMapper;
import com.pxst.resp.ApiResp;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author Chrissy
 * @description 数据库表名还没确立，暂时用原表名代替
 * @since 2023-11-14 16:03:12
 */
@Service
public class SysSelectOptionConfigEntityServiceImpl extends JoinServiceImpl<SysSelectOptionConfigEntityMapper, SysSelectOptionConfigEntity> implements SysSelectOptionConfigEntityService {
    @Resource
    private SysSelectOptionConfigEntityMapper sysSelectOptionConfigEntityMapper;

    @Resource
    private SysMerchantInfoMapper sysMerchantInfoMapper;

    @Override
    public ApiResp index(Long merchantId) {
        SysMerchantInfoEntity merchantInfoEntity = sysMerchantInfoMapper.selectById(merchantId);

        if (ObjectUtils.isEmpty(merchantId)) {
            throw new BusinessException("当前商户不存在！");
        }

        StringBuilder temp = new StringBuilder(SecureUtil.md5(merchantInfoEntity.getId().toString()));

        String hash = temp.substring(temp.length() - 3, temp.length()); //截取最后三位作为hash值

        LambdaQueryWrapper<SysSelectOptionConfigEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysSelectOptionConfigEntity::getType, "SH100_URL");
        List<SysSelectOptionConfigEntity> selectList = sysSelectOptionConfigEntityMapper.selectList(wrapper);

        IntegrationResult result = new IntegrationResult();
        result.setMd5Keys(merchantInfoEntity.getSecret());
        /**
         *设置英文Api文档地址（待定）
         */
        result.setApiEnDoc(null);
        /**
         *设置中文Api文档地址（待定）
         */
        result.setApiCnDoc(null);

        for (SysSelectOptionConfigEntity sysSelectOptionConfigEntity : selectList) {
            result.getIntegrationUrls().add("https://" + sysSelectOptionConfigEntity.getContent() + "/" + merchantInfoEntity.getId() +"-"+ hash);
        }

        return ApiResp.sucess(result);
    }
}
